package cn.msqweb.strategy.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.msqweb.config.WxConfig;
import cn.msqweb.constant.AuthConstants;
import cn.msqweb.domain.LoginMember;
import cn.msqweb.mapper.LginMemberMapper;
import cn.msqweb.mapper.LoginSysUserMapper;
import cn.msqweb.model.SecurityUser;
import cn.msqweb.strategy.LoginStrategy;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * 会员的登录登录策略
 */
@Service(AuthConstants.MEMBER_LOGIN)
public class MemberLoginStrategy implements LoginStrategy {

    @Resource
    private LginMemberMapper lginMemberMapper;
    @Resource
    private WxConfig wxConfig;
    @Override
    public UserDetails realLogin(String username) {
        //获取发送给微信的url地址
        System.out.println("wxConfig.getUrl() = " + wxConfig.getUrl());
        String realUrl = String.format(wxConfig.getUrl(), wxConfig.getAppid(), wxConfig.getAppSecret(),username);
        System.out.println("realUrl = " + realUrl);
        //发送请求
        String wxJsonStr = HttpUtil.get(realUrl);
        if(!StringUtils.hasText(wxJsonStr)){
            throw new InternalAuthenticationServiceException("登录异常");
        }
        //获取 openid
        JSONObject jsonObject = JSONObject.parseObject(wxJsonStr);
        String openid = jsonObject.getString("openid");
        if (!StringUtils.hasText(openid)){
            throw new InternalAuthenticationServiceException("登录异常");
        }
        //判断用户是否存在
        LoginMember loginMember = lginMemberMapper.selectOne(new LambdaQueryWrapper<LoginMember>()
                .eq(LoginMember::getOpenId, openid));
        if (ObjectUtil.isNull(loginMember)){
            loginMember = creationMember(openid);
        }
        if (loginMember.getStatus() != 1){
            throw new InternalAuthenticationServiceException("账号异常");
        }
        //创建全安认证对象（框架的）
        SecurityUser securityUser = creationSecurityUser(loginMember);
        return securityUser;
    }

    private SecurityUser creationSecurityUser(LoginMember loginMember) {
        SecurityUser securityUser = new SecurityUser();
        securityUser.setLoginType(AuthConstants.MEMBER_LOGIN);
        securityUser.setUsername(loginMember.getOpenId());
        securityUser.setPassword(new BCryptPasswordEncoder().encode("WECHAT"));
        securityUser.setOpenId(loginMember.getOpenId());
        securityUser.setStatus(loginMember.getStatus());
        return securityUser;
    }

    private LoginMember creationMember(String openid) {
        //获取当前请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        LoginMember loginMember = new LoginMember();
        loginMember.setCreateTime(new Date());
        loginMember.setStatus(1);
        loginMember.setScore(0);
        loginMember.setOpenId(openid);
        loginMember.setUpdateTime(new Date());
        loginMember.setUserLasttime(new Date());
        loginMember.setUserRegip(request.getRemoteAddr());
        loginMember.setUserLastip(request.getRemoteAddr());
        lginMemberMapper.insert(loginMember);
        return loginMember;
    }

}
